/**
 * Copyright 2010 Victor Egea Hernando
 *
 * RockScript is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 * 
 * RockScript is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with RockScript.  If not, see <http://www.gnu.org/licenses/>.
 */
#include "corelib.h"

namespace paper{

/****************************************************************** 
 * corelib.Debug
 ******************************************************************/

/**************************************************************
 * gets call-stack backtrace
 **************************************************************/
corelib::int32 get_backtrace_hnd( vmachine &vm, method &mp, corelib::uint32 pc ){ 
	//corelib::ustring *str = new corelib::ustring(vm.backtrace());
	//SETREG_STRING(vm,REG_TOOGLE(10),str)
	return 1; // pc++
}

void get_backtrace( vm_class &lib_class ){
	corelib::uint32 idx = 0;
	lib_class.get_method_idx( "mthd_0_backtrace", idx );
	method *m_get_backtrace = lib_class.get_method( idx );

	// allocate memory
	if(	!m_get_backtrace->set_stack_frame_size( 0, 0 ) ){
		std::cout << "error allocating get_backtrace memory" << std::endl;
		return;
	}

	m_get_backtrace->set_flags( paper::FLG_MTHD_STATIC );
	m_get_backtrace->set_cpp_handler( &get_backtrace_hnd );
	m_get_backtrace->add_inst_b(paper::OP_CPPCODE,0,0);
	m_get_backtrace->add_inst_b(paper::OP_RETURN,10,0);
}

/****************************************************************************************
 * loads debug class
 ****************************************************************************************/
void load_debug_header( vmachine &vm ){
	// module class
	vm_class* lib_class;

	/****************************************************************** 
	 * corelib.Debug
	 ******************************************************************/
	corelib::pair<paper::vm_class*, bool> testc = vm.add_class("corelib.Debug");
	// check addition
	if(!testc.second){ return; }

	testc.first->add_method("backtrace","mthd_0_");
}

void load_debug_lib( vmachine &vm ){
	vm_class *lib_class = vm.get_class("corelib.Debug").first;
	// define functions
	get_backtrace( *lib_class );
}

}; // namespace paper;

